if (!window.console){
    window.console = {
        log : function(){}
    }
}

var gorizontalScroll = function (anchorSelector){
	//e.preventDefault();
	//anchorLinkHighlight(this); // Activate this
	
	var $a = $(anchorSelector),
		existScrollLeft = service_scrolling.$wrapper.scrollLeft(),
		scrollLeft = Math.floor($a.offset().left + existScrollLeft - 20); // + отступ 20 px
		
	service_scrolling.$wrapper.stop();
		
	service_scrolling.$wrapper.animate(
		{scrollLeft:scrollLeft},
		500
		/*{
			duration:service_scrolling.timeScroll,
			easing:'easeOutExpo',
			complete:function(){
				
			}
		}*/
	);
	
};

var checkMainScrollAndSlider = function(){
	var currentScrollLeft = service_scrolling.$wrapper.scrollLeft(),
		mainSlider = service_scrolling.mainSlider,
		findI = false;
		
	for (el in mainSlider){
		
		if (currentScrollLeft > mainSlider[el]){
			if (typeof mainSlider[parseInt(el)+1] !== "undefined"){
				if (currentScrollLeft < mainSlider[parseInt(el)+1]){
					findI = el;
				}
			}else {
					findI = el;
			}
		}
		
		if (findI){
			break;
		}
		
	}
	
			//console.log(findI)
	if (findI)
		$(".slider").slider( "option", "value", findI );
	
	//console.log(currentScrollLeft);
	//console.log(mainSlider)
	
	
	
};

// функция для установки значений scrollLeft у основных ссылок в главном окне
updateMainSliderLinks = function(){
		// заполняем массив - sliderValue = scrollLeft;
		var min = $(".slider").slider( "option", "min" );
		var max = $(".slider").slider( "option", "max" );
		var existScrollLeft = service_scrolling.$wrapper.scrollLeft();
		service_scrolling.mainSlider = [];
		
		for (var i = min; i <= max; i++){
			service_scrolling.mainSlider[i] = Math.floor($('#mainSlider_' + i).offset().left + existScrollLeft - 740);		
		}
		
		service_scrolling.mainSlider[service_scrolling.mainSlider.length-1] = service_scrolling.mainSlider[service_scrolling.mainSlider.length-1] + 200;
};

$.fn.stickyFloatGorizontal = function(options, lockBottom) {
	var $obj                = this;
	var parentPaddingLeft    = parseInt($obj.parent().css('padding-left'));
	var startOffset         = $obj.parent().offset().left;
	var opts                = $.extend({ startOffset: startOffset, offsetY: parentPaddingLeft, duration: 200, lockBottom:true }, options);

	$obj.css({ position: 'absolute' });

	if(opts.lockBottom){
		var rightPos = $obj.parent().width() - $obj.width() + parentPaddingLeft;
		if( rightPos < 0 )
			rightPos = 0;
	}
	
	if (startOffset < 0){
		startOffset = 0;
	}

	service_scrolling.$wrapper.scroll(function () {
		$obj.stop();

		var pastStartOffset         = service_scrolling.$wrapper.scrollLeft() > opts.startOffset;
		var objFartherThanLeftPos    = $obj.offset().left > startOffset;
		var objBiggerThanWindow     = $obj.outerWidth() < service_scrolling.$wrapper.width();	
		
		if( (pastStartOffset || objFartherThanLeftPos) && objBiggerThanWindow ){
			var newpos = (service_scrolling.$wrapper.scrollLeft() - startOffset + opts.offsetY );
			
			//console.log("scrollLeft: "+service_scrolling.$wrapper.scrollLeft() + " => startOffset: " + startOffset + " => rightPos: " + rightPos)
			
			if ( newpos > rightPos )
				newpos = rightPos;
			if ( service_scrolling.$wrapper.scrollLeft() < opts.startOffset )
				newpos = parentPaddingLeft;
					
			//console.log(newpos)	

			$obj.animate({ left: newpos }, opts.duration );
		}
	});
};



	var service_scrolling = {};
    
	$(document).ready(function(){
		service_scrolling.$content = $('.container');
		service_scrolling.$wrapper = $('.wrapper');
		service_scrolling.mainPadding = parseInt(service_scrolling.$content.css('padding-left'));
		service_scrolling.contentPadding = parseInt(service_scrolling.$content.css('padding-right'));
		service_scrolling.scrollingMax = 0;
		service_scrolling.scrolling = service_scrolling.$wrapper.scrollLeft();
		service_scrolling.speedScroll = 100;
		service_scrolling.timeScroll = 1000;
		
		/////////////////////////////////////////////////////////////////////// ГЛАВНЫЙ СЛАЙДЕР //////////////////////////////////////////////////////////////////////////
	
		$( ".slider" ).slider({
			animate: true,
			range: "min",
			value: 1,
			min: 1,
			max: (isArchive ? 8 : 9),
			step: 1,
			//this gets a live reading of the value and prints it on the page
			slide: function( event, ui ) {
				//console.log(ui.handle)
				//$( "#slider-result" ).html( ui.value );
				gorizontalScroll('#mainSlider_' + ui.value);
			},
			//this updates the hidden form field so we can submit the data using a form
			change: function(event, ui) {
				gorizontalScroll('#mainSlider_' + ui.value);
				
				//console.log(event);
				
				//$('#hidden').attr('value', ui.value);
			}
		});		
		
		
		updateMainSliderLinks();

		
		
		
		var action = 0;
		
		if ($.browser.opera) service_scrolling.$wrapper.animate({scrollLeft:service_scrolling.scrolling + 1},1).scrollLeft(service_scrolling.scrolling);
		
	
		// для прокрутки колесиком главного контента //
		service_scrolling.$wrapper.mousewheel(function(event, delta){
		
			var $sp_block = $(event.target).parents("div.sp-block");
			var sp_block = $sp_block[0];
			var noScroll = false;
			
			if ($sp_block.length){
				// если есть лифт вертикальной прокрутки
				if (sp_block.offsetHeight < sp_block.scrollHeight){
					// если нужно прокручивать вертикальный блок
					noScroll = true;
				}
				
			} // ?????????????
			
			
			service_scrolling.scrollingMax = service_scrolling.$content.width()+ service_scrolling.contentPadding + service_scrolling.mainPadding - $('body').width();
			
			if(/*!action && */service_scrolling.scrolling != $(this).scrollLeft()) service_scrolling.scrolling = $(this).scrollLeft();

			
			if( service_scrolling.scrollingMax > 0 && ((service_scrolling.scrolling > 0 && delta > 0) || (service_scrolling.scrolling < service_scrolling.scrollingMax && delta < 0)) && !noScroll){
				action = 1;
				
				if(service_scrolling.scrolling != $(this).scrollLeft() && service_scrolling.scrolling > 0 && service_scrolling.scrolling < scrollingMax) scrolling = 
					service_scrolling.scrolling - (delta * service_scrolling.speedScroll);
				else service_scrolling.scrolling = $(this).scrollLeft() - (delta * service_scrolling.speedScroll);
				
				if (service_scrolling.scrolling < 0) service_scrolling.scrolling = 0;
				if (service_scrolling.scrolling > service_scrolling.scrollingMax) service_scrolling.scrolling = service_scrolling.scrollingMax;
				
				
				//$(this).stop().prop("scrollLeft", scrolling);
				checkMainScrollAndSlider();

				$(this).stop().scrollLeft(service_scrolling.scrolling);
				
				event.stopPropagation();
				event.preventDefault();
			}
		});
		
		
		
		
		checkMainScrollAndSlider();
		

		// инициализация скроллера программы
		$("#programmSlider").stickyFloatGorizontal({duration: 0});
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	  // Обычные окошки thickbox
		if ($("a.thickbox").length > 0){
			thickBox_init(); //инициализируем окошки
		}
		
		// адрес после хоста с ?
		var search = window.location.search, // string
			link = ["reg", "about", "anons", "listener", "sponsor", "speaker", "map", "contacts"],
			size = link.length,
			i = 0,
			re = new RegExp("promo=(\\w+)", "i"),
			found = search.match(re),
			promoKod = false,
			rePartner = new RegExp("(p|partner)=(\\w+)", "i"),
			foundPartner = search.match(rePartner),
			partnerKod = false;
			
					
		if (found){
			promoKod = found[1] || false;
		}

		if (foundPartner){
			partnerKod = foundPartner[2] || false;
		}

		// добавляем промо код в адрес рег формы
		
		if (promoKod){
			var href = $("a.reg").prop("href");
			
			href += "&promo=" + promoKod;			
			$("a.reg").prop("href", href);
		} else if (partnerKod){
			// добавляем партнерку в адрес рег формы
			var href = $("a.reg").prop("href");
			
			href += "&partner=" + partnerKod;		
			$("a.reg").prop("href", href);			
		}
		
		
		if (search){
		
			// ищем ссылки thickbox в адресе
			
			for ( ; i < size; i ++){
				if ( new RegExp(link[i], "i").test(search) ) {
					// пытаемся открыть диалог thickbox
					var aLink = $("a." + link[i]).get(0),
					t = aLink.title || aLink.name || null,
					a = aLink.href || aLink.alt,	
					g = aLink.rel || false;
															
					tb_show(t,a,g);
					aLink.blur();
				}
			}
		}
		
		
		
	});